<template>
  <div class="list-menu">
    <div class="menu-header">
      <h3>任务列表</h3>
      <el-button
          type="primary"
          size="small"
          @click="openForm(null)"
      >
        <el-icon><plus /></el-icon>
        <span>新建列表</span>
      </el-button>
    </div>

    <el-menu
        :default-active="currentListId?.toString()"
        @select="selectList"
    >
      <template v-if="loading">
        <div class="loading-container">
          <el-icon class="loading-icon"><loading /></el-icon>
        </div>
      </template>

      <template v-else-if="error">
        <div class="error-message">{{ error }}</div>
      </template>

      <template v-else>
        <template v-for="list in lists.filter(item => item && item.id !== undefined)" :key="list.id">
          <el-menu-item :index="list.id.toString()">
            <template #title>
              <div class="list-item">
                <el-icon><folder /></el-icon>
                <span class="list-name">{{ list.name }}</span>
                <div class="list-actions">
                  <el-button
                      text
                      size="small"
                      @click.stop="openForm(list)"
                  >
                    <el-icon><edit /></el-icon>
                  </el-button>
                  <el-button
                      text
                      size="small"
                      @click.stop="deleteList(list.id)"
                  >
                    <el-icon><delete /></el-icon>
                  </el-button>
                </div>
              </div>
              <div class="list-date">
                {{ formatDate(list.createdAt) }}
              </div>
            </template>
          </el-menu-item>
        </template>
      </template>
    </el-menu>

    <list-form
        v-model="showForm"
        :list="editingList"
        @success="handleFormSuccess"
    />
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { storeToRefs } from 'pinia'
import { useListStore } from '@/store/list.ts'
import { Folder, Plus, Edit, Delete, Loading } from '@element-plus/icons-vue'
import ListForm from './ListForm.vue'

const listStore = useListStore()
const { lists, currentListId, loading, error } = storeToRefs(listStore)

const showForm = ref(false)
const editingList = ref(null)

const openForm = (list) => {
  editingList.value = list 
    ? { 
        id: list.id,
        name: list.name || '',
        createdAt: list.createdAt 
      } 
    : { name: '' }
  console.log('Editing list:', editingList.value) // 调试用
  showForm.value = true
}

const selectList = (index) => {
  listStore.setCurrentList(parseInt(index))
}

const deleteList = async (id) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个列表吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await listStore.deleteList(id)
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

const handleFormSuccess = async (formData) => {
  try {
    console.log('收到表单数据:', formData)
    if (editingList.value?.id) {
      console.log('准备更新列表:', editingList.value.id)
      await listStore.updateList(editingList.value.id, formData)
    } else {
      console.log('准备创建新列表')
      await listStore.createList(formData)
    }
    ElMessage.success(editingList.value?.id ? '列表更新成功' : '列表创建成功')
    await listStore.fetchLists()
    console.log('列表数据已刷新:', listStore.lists)
    showForm.value = false
  } catch (error) {
    console.error('表单提交失败:', error)
    ElMessage.error(error.message || '操作失败')
  }
}

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleDateString()
}

// 初始化加载列表
listStore.fetchLists()
</script>

<style scoped>
.list-menu {
  height: 100%;
  border-right: 1px solid var(--el-border-color);
}

.menu-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid var(--el-border-color);
}

.list-item {
  display: flex;
  align-items: center;
  width: 100%;
}

.list-name {
  flex: 1;
  margin: 0 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.list-actions {
  display: flex;
  opacity: 0;
  transition: opacity 0.2s;
}

.el-menu-item:hover .list-actions {
  opacity: 1;
}

.list-date {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 4px;
}

.loading-container {
  padding: 16px;
  text-align: center;
}

.loading-icon {
  animation: rotate 2s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.error-message {
  padding: 16px;
  color: var(--el-color-error);
}
</style>